package org.burning.crm.settings.service;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import org.springframework.stereotype.Service;

/**
 * 短信服务类，用于发送验证码等短信通知
 */
@Service
public class SmsService {

    // 短信宝用户名
    private final String username = "chenhongfei";
    // 短信宝密码
    private final String password = "3a5111cca1aa4685989f9104f33b4d6d";
    // API请求地址
    private final String apiUrl = "http://api.smsbao.com/sms";
    // 短信签名
    private final String smsSign = "【微步】";

    /**
     * 发送验证码短信
     *
     * @param phone 接收短信的手机号码
     * @param code 验证码
     * @return 发送是否成功
     */
    public boolean sendVerificationCode(String phone, String code) {
        // 构建短信内容
        String content = smsSign + "您的验证码是" + code + "，5分钟内有效。若非本人操作请忽略此消息。";

        // 构建请求参数
        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(username).append("&");
        httpArg.append("p=").append(md5(password)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(encodeUrlString(content, "UTF-8"));

        // 发送请求并获取结果
        String result = request(apiUrl, httpArg.toString());
        // 返回发送结果，"0"表示发送成功
        return "0".equals(result);
    }


    /**
     * 发送短信 群发
     * @param phone
     * @param content
     * @return
     */
    public boolean sendAll(String phone, String content) {
        // 构建短信内容
        String content1 = smsSign + content;

        // 构建请求参数
        StringBuffer httpArg = new StringBuffer();
        httpArg.append("u=").append(username).append("&");
        httpArg.append("p=").append(md5(password)).append("&");
        httpArg.append("m=").append(phone).append("&");
        httpArg.append("c=").append(encodeUrlString(content1, "UTF-8"));

        // 发送请求并获取结果
        String result = request(apiUrl, httpArg.toString());
        // 返回发送结果，"0"表示发送成功
        return "0".equals(result);
    }

    /**
     * 发起HTTP请求
     *
     * @param httpUrl 请求地址
     * @param httpArg 请求参数
     * @return 请求结果
     */
    private String request(String httpUrl, String httpArg) {
        BufferedReader reader = null;
        String result = null;
        StringBuffer sbf = new StringBuffer();
        httpUrl = httpUrl + "?" + httpArg;

        try {
            URL url = new URL(httpUrl);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            connection.connect();
            InputStream is = connection.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String strRead = reader.readLine();
            if (strRead != null) {
                sbf.append(strRead);
                while ((strRead = reader.readLine()) != null) {
                    sbf.append("\n");
                    sbf.append(strRead);
                }
            }
            reader.close();
            result = sbf.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 计算MD5值
     *
     * @param plainText 明文
     * @return MD5值
     */
    private String md5(String plainText) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(plainText.getBytes());
            byte[] b = md.digest();
            StringBuffer buf = new StringBuffer("");
            for (byte value : b) {
                int i = value;
                if (i < 0) i += 256;
                if (i < 16) buf.append("0");
                buf.append(Integer.toHexString(i));
            }
            return buf.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * URL编码
     *
     * @param str 待编码的字符串
     * @param charset 字符集
     * @return 编码后的字符串
     */
    private String encodeUrlString(String str, String charset) {
        try {
            return java.net.URLEncoder.encode(str, charset);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
